package com.aaa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class DBSecurityConfig  {
 @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder(); //设定加密方式
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();//允许页面加载iframe
        http.csrf().disable()
                .cors(Customizer.withDefaults());

                http.formLogin() //配置登录规则
                .loginPage("/login.html") //设置显示登录页面的请求路径
                .loginProcessingUrl("/login")//设置登录提交请求路径

                .defaultSuccessUrl("/index.html")//登录成功后跳转的页面，不能使用.successForwardUrl
                .failureUrl("/login.html?error")//登录失败后跳转的页面
                .permitAll()//设置登录相关的处理不做权限校验，全部许可
                       // .successHandler(new MyAuthenticationSuccessHandler()) //前后端分离时验证成功时的处理
                .and()
                .logout() //配置登出
                .logoutUrl("/logout")  //登出的请求路径
                .logoutSuccessUrl("/login.html")  //登出成功后的路径
                .permitAll()
                .and()
                .authorizeRequests()//配置其它请求授权规则
                .antMatchers("/css/**","/js/**","/img/**").permitAll()
                .antMatchers("/test1").hasRole("admin")//设置test1请求需要admin角色才能访问
                .antMatchers("/test2").hasAuthority("user:query")//设置test2请求需要user角色才能访问
                .antMatchers("/user/userAdd").permitAll() //放行注册请求路径
                .antMatchers("/user/userCheckRepeat").permitAll() //放行用户名查重请求路径
                .anyRequest().authenticated();//其他请求都需要权限校验，合法用户可以访问
        return http.build();    //创建 SecurityFilterChain 对象
    }
}
